<template>
  <view class="product-container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <text class="title">产品列表</text>
      <view class="button-group">
        <button class="refresh-btn" @click="refreshData">⟳</button>
        <button class="add-device-btn" @click="toAddDevice">新增设备</button> 
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </view>
    </view>
    
    <!-- 产品列表 -->
    <view class="product-list">
      <!-- 列表项 -->
      <view 
        class="product-item" 
        v-for="(item, index) in productList" 
        :key="index" 
        @click="goToEdit(item.productSNo)"
        @longpress="handleLongPress(item, index)"
      >
        <view class="product-info">
          <view class="info-row">
            <text class="label">产品序列号：</text>
            <text class="value">{{ item.productSNo }}</text>
          </view>
          <view class="info-row">
            <text class="label">设备标识：</text>
            <text class="value">{{ item.deviceId }}</text>
          </view>
          <view class="info-row">
            <text class="label">数据时间：</text>
            <text class="value">{{ formatDate(item.updateTime) }}</text>
          </view>
          <view class="info-row">
            <text class="label">是否在线：</text>
            <text class="value" :class="{ 'online': item.onlineStatus === '在线', 'offline': item.onlineStatus === '离线', 'unconnected': item.onlineStatus === '未上过线' }">
              {{ item.onlineStatus }}
            </text>
          </view>
          <view class="info-row">
            <text class="label">安装地点：</text>
            <text class="value">{{ item.installationLocation }}</text>
          </view>
          <view class="info-row">
            <text class="label">应用场景：</text>
            <text class="value">{{ item.applicationScenario }}</text>
          </view>
          <view class="info-row">
            <text class="label">出线数量：</text>
            <text class="value line-count">{{ item.lineNum || 0 }}路</text>
          </view>
        </view>
        
        <!-- 二维码展示（如果有） 
        <view class="qr-code" v-if="item.base64QrCode">
          <image :src="'data:image/png;base64,' + item.base64QrCode" mode="widthFix" class="qr-img"></image>
        </view> -->
        
        <!-- 长按提示 -->
        <view class="long-press-hint">
          <text class="hint-text"></text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="productList.length === 0 && !loading">
        <image src="/static/empty.png" class="empty-img"></image>
        <text class="empty-text">暂无产品数据</text>
      </view>
      
      <!-- 加载中 -->
      <view class="loading-state" v-if="loading">
        <uni-loading-icon size="24" color="#2980ff"></uni-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 分页控件 -->
    <view class="pagination" v-if="total > 0">
      <button 
        class="page-btn" 
        @click="prevPage" 
        :disabled="currentPage <= 1 || loading"
      >
        上一页
      </button>
      <view class="page-info">
        <text>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</text>
        <text class="total-count">共 {{ total }} 条</text>
      </view>
      <button 
        class="page-btn" 
        @click="nextPage" 
        :disabled="currentPage >= totalPages || loading"
      >
        下一页
      </button>
    </view>
  </view>
</template>

<script>
import config from '../../config/index.js'

export default {
  data() {
    return {
      productList: [], // 产品列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总条数
      totalPages: 0, // 总页数
      loading: false, // 加载状态
      deletingIndex: -1, // 正在删除的产品索引
    };
  },
  
  onLoad() {
    // 检查是否已登录
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 加载产品数据
    this.loadProductData();
  },
  
  onShow() {
    // 检查是否需要刷新
    const needRefresh = uni.getStorageSync('needRefreshProductList');
    if (needRefresh) {
      uni.removeStorageSync('needRefreshProductList');
      this.refreshData();
    }
  },
  
  methods: {
    // 跳转到编辑页面
    goToEdit(productSNo) {
      uni.navigateTo({
        url: `/pages/product-edit/product-edit?productSNo=${encodeURIComponent(productSNo)}`
      });
    },
    
    toAddDevice() {
      uni.navigateTo({
        url: '/pages/add-device/add-device' 
      });
    },
    
    // 处理长按事件
    handleLongPress(item, index) {
      console.log('长按产品:', item.productSNo);
      
      // 显示删除确认对话框
      uni.showModal({
        title: '确认删除',
        content: `确定要删除产品"${item.productSNo}"吗？\n\n删除后无法恢复！`,
        confirmText: '确认删除',
        confirmColor: '#ff4757',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.deleteProduct(item.productSNo, index);
          }
        }
      });
    },
    
    // 删除产品
    async deleteProduct(productSNo, index) {
      if (this.deletingIndex !== -1) {
        return; // 防止重复删除
      }
      
      this.deletingIndex = index;
      
      try {
        const token = uni.getStorageSync('token');
        
        // 显示删除中提示
        uni.showLoading({
          title: '删除中...',
          mask: true
        });
        
        const result = await new Promise((resolve, reject) => {
          uni.request({
            url: `${config.baseURL}/productDetail/deleteByProductSNo/${encodeURIComponent(productSNo)}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            success: (res) => {
              resolve(res);
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
        
        uni.hideLoading();
        
        if (result.statusCode === 200) {
          const data = result.data;
          if (data.code === 0) {
            // 删除成功
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000
            });
            
            // 从列表中移除该项
            this.productList.splice(index, 1);
            this.total--;
            
            // 重新计算总页数
            this.totalPages = Math.ceil(this.total / this.pageSize);
            
            // 如果当前页没有数据了，且不是第一页，则跳转到上一页
            if (this.productList.length === 0 && this.currentPage > 1) {
              this.currentPage--;
              this.loadProductData();
            }
            
            console.log('产品删除成功:', productSNo);
          } else {
            // 业务错误
            uni.showToast({
              title: data.msg || '删除失败',
              icon: 'none',
              duration: 2000
            });
            console.error('删除失败:', data.msg);
          }
        } else {
          // HTTP错误
          uni.showToast({
            title: `删除失败: ${result.statusCode}`,
            icon: 'none',
            duration: 2000
          });
          console.error('删除HTTP错误:', result.statusCode);
        }
      } catch (error) {
        uni.hideLoading();
        console.error('删除产品异常:', error);
        uni.showToast({
          title: '删除失败，请重试',
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.deletingIndex = -1;
      }
    },
    
    // 刷新数据方法
    refreshData() {
      this.currentPage = 1;
      this.loadProductData();
      uni.showToast({ title: '正在刷新...', icon: 'none', duration: 1000 });
    },
    
    // 加载产品数据
    async loadProductData() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const token = uni.getStorageSync('token');
        new Promise((resolve, reject) => {
          uni.request({
            url: `${config.baseURL}/product/pageWithDetail`,
            method: 'GET',
            data: {
              pageNum: this.currentPage,
              pageSize: this.pageSize
            },
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              resolve(res);
            },
            fail: (err) => {
              reject(err);
            }
          });
        }).then((result) => {
          const data = result.data;
          console.log('=== 产品列表数据 ===');
          console.log('完整响应:', data);
          if (data.code === 0) {
            this.productList = data.data.records || [];
            this.total = data.data.total || 0;
            this.totalPages = Math.ceil(this.total / this.pageSize);
            
            // 调试：检查每个产品的出线数量
            this.productList.forEach((item, index) => {
              console.log(`产品${index + 1}:`, {
                productSNo: item.productSNo,
                lineNum: item.lineNum,
                lineNumType: typeof item.lineNum,
                deviceId: item.deviceId
              });
            });
          } else {
            uni.showToast({ title: data.msg || '获取数据失败', icon: 'none' });
          }
        }).catch((error) => {
          console.error('获取产品数据失败', error);
          uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
        }).finally(() => {
          this.loading = false;
        });
      } catch (error) {
        console.error('获取产品数据异常', error);
        this.loading = false;
        uni.showToast({ title: '加载失败，请重试', icon: 'none' });
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(date.getHours());
      const minutes = this.padZero(date.getMinutes());
      const seconds = this.padZero(date.getSeconds());
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 补零
    padZero(num) {
      return num < 10 ? '0' + num : '0' + num;
    },
    
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.loadProductData();
        uni.pageScrollTo({ scrollTop: 0 });
      }
    },
    
    // 下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.loadProductData();
        uni.pageScrollTo({ scrollTop: 0 });
      }
    },
    
    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('token');
            uni.removeStorageSync('username');
            uni.redirectTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.product-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  box-sizing: border-box;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #2980ff;
  color: #fff;
  box-sizing: border-box;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 10rpx;
}

.refresh-btn {
  color: #fff;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 8rpx;
  font-size: 32rpx;
  padding: 10rpx 15rpx;
  height: auto;
  line-height: normal;
  box-sizing: border-box;
}

.add-device-btn {
  color: #fff;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 8rpx;
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  height: auto;
  line-height: normal;
  box-sizing: border-box;
}

.logout-btn {
  color: #fff;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 8rpx;
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  height: auto;
  line-height: normal;
  box-sizing: border-box;
}

.product-list {
  padding: 15rpx 20rpx;
  box-sizing: border-box;
}

.product-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 12rpx 20rpx;
  margin-bottom: 4rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
}

.info-row {
  display: flex;
  margin-bottom: 6rpx;
  line-height: 1.2;
  box-sizing: border-box;
}

.info-row:last-child {
  margin-bottom: 0 !important;
}

.label {
  font-size: 26rpx;
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
  box-sizing: border-box;
}

.value {
  font-size: 26rpx;
  color: #333;
  word-break: break-all;
  box-sizing: border-box;
}

.qr-code {
  margin-top: 8rpx;
  display: flex;
  justify-content: center;
  box-sizing: border-box;
}

.qr-code[v-if] { 
  display: flex;
}

.qr-img {
  width: 120rpx;
  height: 120rpx;
  box-sizing: border-box;
}

/* 长按提示样式 */
.long-press-hint {
  position: absolute;
  top: 10rpx;
  right: 15rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 4rpx 8rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  opacity: 0.7;
  pointer-events: none;
}

.hint-text {
  font-size: 20rpx;
  color: #fff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  box-sizing: border-box;
}

.empty-img {
  width: 180rpx;
  height: 180rpx;
  opacity: 0.5;
  margin-bottom: 20rpx;
  box-sizing: border-box;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  box-sizing: border-box;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  box-sizing: border-box;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
  margin-top: 15rpx;
  box-sizing: border-box;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 20rpx;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  box-sizing: border-box;
}

.page-btn {
  width: 140rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #2980ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.page-btn:disabled {
  background-color: #c9d8e9;
  color: #fff;
  box-sizing: border-box;
}

.page-info {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  box-sizing: border-box;
}

.total-count {
  display: block;
  font-size: 24rpx;
  margin-top: 5rpx;
  color: #999;
  box-sizing: border-box;
}

.online {
  color: green;
}

.offline {
  color: red;
}

.unconnected {
  color: gray;
}

/* 出线数量样式 */
.line-count {
  color: #2980ff;
  font-weight: 600;
  background-color: #f0f8ff;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

/* 紧凑模式：减少没有二维码的卡片底部间距 */
.product-item:not(:has(.qr-code)) {
  padding-bottom: 8rpx;
}

/* 进一步减少信息行间距 */
.info-row:not(:last-child) {
  margin-bottom: 4rpx;
}
</style>